import { useAppSelector } from "@/store/hooks";
import { TZ } from "@/utils/env";
import { Card, DatePicker, Button, Select, Form, message, Modal } from "antd";
import type { FormProps } from 'antd';
import type { Dayjs } from "dayjs";
import dayjs from "@/utils/dayjs";
import { reRun } from "@/store/reRun/reRunAPI";

const { RangePicker } = DatePicker;

type FieldType = {
  time?: Dayjs[];
  data_type?: number;
};

export default function Filter() {
  const { config: { data: { data: { run_stat_type_map = [] } = {} } = {} } = {} } = useAppSelector(state => state.app)
  const onFinish: FormProps<FieldType>['onFinish'] = (values) => {
    Modal.confirm({
      title: '确认重跑吗',
      onOk: () => new Promise<void>((resolve, reject) => {
        if (!values.time) {
          reject()
          return
        }
        reRun({
          start_t: values.time[0].unix(),
          end_t: values.time[1].unix(),
          data_type: values.data_type as number
        }).then(() => {
          message.success('操作成功')
          resolve()
        }).catch(reject)
      })
    })
  };

  return (
    <Card>
      <Form onFinish={onFinish} initialValues={{
        time: [dayjs().tz(TZ).startOf('day'), dayjs().tz(TZ).endOf('day')]
      }}>
        <Form.Item<FieldType> name='time' label='时间' rules={[{ required: true, message: '必选' }]}>
          <RangePicker showTime />
        </Form.Item>
        <Form.Item<FieldType> name='data_type' label='统计数据类型' rules={[{ required: true, message: '必选' }]}>
          <Select options={run_stat_type_map} className="max-w-[140px]" />
        </Form.Item>
        <Form.Item<FieldType>>
          <Button type="primary" htmlType="submit">
            重跑数据
          </Button>
        </Form.Item>
      </Form>
    </Card>
  );
}
